//
//  UIButton_Ex.swift
//  Dawn
//
//  Created by cuicheng on 2021/9/11.
//

import UIKit

public enum UIButtonContentStyle: Int {
    case none
    /// 标题在左, 图片在右
    case left
    /// 标题在右, 图片在左
    case right
    /// 标题在上, 图片在下
    case top
    /// 标题在下, 图片在上
    case bottom
}

public extension DawnWrapper where Base: UIButton {

    /// 设置button图片和文本布局
    /// - Parameters:
    ///   - style: 布局样式，以标题为基准
    ///   - space: 文本和图片间距
    func set(style: UIButtonContentStyle, space: CGFloat) {
        if style == .none { return }
        // 1. 得到imageView和titleLabel的宽、高
        let imageWith = base.imageView?.frame.size.width
        let imageHeight = base.imageView?.frame.size.height

        let labelWidth = (base.titleLabel?.intrinsicContentSize.width)!
        let labelHeight = (base.titleLabel?.intrinsicContentSize.height)!
        // 2. 声明全局的imageEdgeInsets和labelEdgeInsets
        
        var imageEdgeInsets:
            UIEdgeInsets = .zero
        var labelEdgeInsets:
            UIEdgeInsets = .zero
        
        // 3. 根据style和space得到imageEdgeInsets和labelEdgeInsets的值
        switch style {
        case .bottom:
            imageEdgeInsets = UIEdgeInsets(top: -labelHeight-space/2.0, left: 0, bottom: 0, right: -labelWidth)
            labelEdgeInsets = UIEdgeInsets(top: 0, left: -imageWith!, bottom: -imageHeight! - space/2.0, right: 0)
            break
        case .right:
            imageEdgeInsets = UIEdgeInsets(top: 0, left: -space/2.0, bottom: 0, right: space/2.0)
            labelEdgeInsets = UIEdgeInsets(top: 0, left: space/2.0, bottom: 0, right: -space/2.0)
            break
        case .top:
            imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: -labelHeight-space/2.0, right: -labelWidth)
            labelEdgeInsets = UIEdgeInsets(top: -imageHeight!-space/2.0, left: -imageWith!, bottom: 0, right: 0)
            break
        case .left:
            imageEdgeInsets = UIEdgeInsets(top: 0, left: labelWidth+space/2.0, bottom: 0, right: -labelWidth-space/2.0)
            labelEdgeInsets = UIEdgeInsets(top: 0, left: -imageWith!-space/2.0, bottom: 0, right: imageWith!+space/2.0)
            break
        default:
            break
        }
        // 4. 赋值
        base.titleEdgeInsets = labelEdgeInsets
        base.imageEdgeInsets = imageEdgeInsets
    }
}

extension UIButton {
    func iconTitle(_ title: String, fontSize: CGFloat, for state: UIControl.State) {
        setTitle(title, for: state)
        titleLabel?.font = UIFont(name: "baseIcon", size: fontSize)
    }
}
